package qc.gateway.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.gateway.entity.QcApiLogs;
import qc.gateway.repository.QcApiLogRepository;

import java.util.Date;

/**
 * 渠成gateway全局日志Service，用于记录每个请求和响应的日志
 *
 * @author QuCheng Tech
 */
@Service
public class QcApiLogService {
    private QcApiLogRepository repository;

    @Autowired
    public void setQCGlobalLogRepository(QcApiLogRepository repository) {
        this.repository = repository;
    }

    /***
     * 添加接口访问日志，一次完成request和response所有信息的写入
     *
     * @return java.lang.String
     * @author QuCheng Tech
     * @since 2023/11/7
     */
    public String add(String id, Date tm, String method, String url, String host, String params, String body, String token, Integer status, String rawData, Integer timespan, String result) {
        QcApiLogs en = new QcApiLogs();
        en.setID(id);
        en.setTM(tm);
        en.setMETHOD(method);
        en.setURL(url);
        en.setHOST(host);
        if (!StringUtils.isBlank(params))
            en.setPARAMS(params);
        if (!StringUtils.isBlank(body))
            en.setBODY(body);
        en.setTOKEN(token);
        en.setSTATUS(status);
        if (!StringUtils.isBlank(rawData))
            en.setDATA(rawData);
        en.setTS(timespan);
        if (!StringUtils.isBlank(result))
            en.setRESULT(result);

        if (repository.insert(en) < 0x1)
            return QCUnifyReturnValue.Warn("保存失败");

        return QCUnifyReturnValue.Success();
    }
}
